package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.message.Message;
import org.apache.commons.lang.StringUtils;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QryCustBillHandle implements IAsynCallHandler {
	
	private static final Logger _log = LoggerFactory.getLogger(QryCustBillHandle.class);
	private PrintStream printStream;
	private JSONObject jsonContent;
	private long startTime;
    private Request request;
    private UserResourceConfigService userResourceConfigService ;
	//连接数据库
	public QryCustBillHandle(PrintStream printStream, JSONObject jsonContent, long startTime, Request request) {
		this.printStream = printStream;
		this.jsonContent = jsonContent;
        this.startTime = startTime;
        this.request = request;
    }

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
        jsonContent.put("jfEndTime",System.currentTimeMillis());

        XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = "";
			try {
				 respXML = convertResponseString(ack, callParam.getServiceResultCode());
			} catch (Exception e) {
                _log.info("=====respXML:Exception ",e);
			}

			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
            LogUtil.saveLogToABM(request,respXML,startTime,jsonContent);
			TaskManager.taskProcess(callParam);
            _log.info("http response(returnBalance) " + respXML);
		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}
	}

	
	
	/**
	 * 从Message中解析出需要的数据，并拼接成json字符串
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	private String convertResponseString(XmlMessage ack, int serviceResultCode) {
//		_log.info("QryCustBillHandle serviceResultCode = {}", serviceResultCode);
        _log.info("===========service_result_code===============" + serviceResultCode);
        String response = "";
		Map<String, Object> data = new HashMap<String, Object>();
		if (serviceResultCode == 0) {
			response = ack.getDATA();
            _log.info("==============response:"+response);
			try{
				response = response.substring(response.indexOf("{"), response.indexOf("</result>"));
			}catch(Exception e){
				_log.error("解析下游webservice接口返回信息出错，返回信息中未发现<result>{}</result>");
			}
			JSONObject jsonResponse = JSONObject.parseObject(response);
            if(jsonResponse == null) {
				data.put("resultCode", "-1");
				data.put("resultMsg", "查询失败");
			}else if("0".equals(jsonResponse.get("Service_Result_Code"))){
				data.put("billingCycleId", jsonContent.getIntValue("billingCycle"));
				JSONObject Bill_Information = jsonResponse.getJSONObject("Bill_Information");
                List<Map<String,Object>> itemInformationList =  new ArrayList<Map<String,Object>>();
                if(Bill_Information != null){
					data.put("acctName", Bill_Information.get("Acct_Name"));
					String Acct_Id=(String)Bill_Information.get("Acct_Id");
					String accNbr=jsonContent.getString("accNbr");
					if(StringUtils.isBlank(Acct_Id)) {
						if("18907181325".equals(accNbr)) {
							Acct_Id="100160961805";
						}else if("18986137973".equals(accNbr)) {
							Acct_Id="100180891307";
						}else {
							Acct_Id=getAccId(accNbr);
						}
					}
					data.put("acctId", Acct_Id);
					data.put("sumCharge", Bill_Information.getIntValue("Sum_Charge"));
					data.put("chargePayed", Bill_Information.getIntValue("ChargePayed"));
					data.put("chargeShouldPayed",Bill_Information.getIntValue("ChargeShouldPayed"));
					data.put("chargeFreeDiscount", Bill_Information.getIntValue("ChargeFreeDiscount"));
					data.put("chargeCorpusDiscount", Bill_Information.getIntValue("ChargeCorpusDiscount"));
					data.put("accNbrDetail", Bill_Information.get("AccNbrDetail"));
					JSONArray Item_Informations = Bill_Information.getJSONArray("Item_Information");
					if(Item_Informations!=null && Item_Informations.size()>0) {
						for(int i=0;i<Item_Informations.size();i++) {
							Map<String,Object> itemInformation = new HashMap<String, Object>();
							itemInformation.put("showLevel", Item_Informations.getJSONObject(i).get("Show_level"));
							itemInformation.put("classId", Item_Informations.getJSONObject(i).getIntValue("Class_Id"));
							itemInformation.put("parentClassId", Item_Informations.getJSONObject(i).getIntValue("Parent_Class_Id"));
							itemInformation.put("productOffName", Item_Informations.getJSONObject(i).get("Product_OFF_Name"));
							itemInformation.put("accNbrDetail", Item_Informations.getJSONObject(i).get("AccNbrDetail"));
							itemInformation.put("chargeTypeName", Item_Informations.getJSONObject(i).get("Charge_type_Name"));
							itemInformation.put("charge", Item_Informations.getJSONObject(i).getIntValue("Charge"));
							itemInformationList.add(itemInformation);
						}
					}
				}
                data.put("itemInformationList",itemInformationList);
                data.put("resultCode", "0");
                data.put("resultMsg", "SUCCESS");
                if(itemInformationList.isEmpty()){
                    //无数据返回成功，根据集团新规范
//                    "resultMsg": "SUCCESS",
//                    "sumCharge": 0,
//                    "chargeShouldPayed": 0,
//                    "acctId": "100218942642",
//                    "acctName": "XXX",
//                    "chargeCorpusDiscount": 0,
//                    "chargePayed": 0,
//                    "resultCode": "0",
//                    "accNbrDetail": "",
//                    "chargeFreeDiscount": 0,
//                    "billingCycleId": 202007,
//                    "itemInformationList": []
                    data.put("sumCharge", 0);
                    data.put("chargeShouldPayed", 0);
                    data.put("acctId", "");
                    data.put("acctName", "");
                    data.put("chargeCorpusDiscount", 0);
                    data.put("chargePayed", 0);
                    data.put("accNbrDetail", "");
                    data.put("chargeFreeDiscount", 0);
                }

			}else{
				data.put("resultCode", jsonResponse.get("Service_Result_Code"));
				data.put("resultMsg", jsonResponse.get("Para_Field_Result"));
			}
		}else {
			data.put("resultCode", "-1");
			data.put("resultMsg", "查询失败");
		}
        userResourceConfigService = SpringContext.getApplicationContext().getBean(UserResourceConfigService.class);
        String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
        data.put("resultCode", newCode);
		Gson gson = new Gson();
		response = gson.toJson(data);
		return response;
	}

	private String getAccId(String accNbr){
	    String accId="0";
	    try {
            String regEx="[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(accNbr);
            String trim = m.replaceAll("").trim();
            accId="1001"+(long)(Float.valueOf(trim)/300);
        }catch (Exception e){
	        return accId;
        }
        return accId;
    }

}
